//
//  SquareViewController.swift
//  lottery
//
//  Created by admin on 16/2/4.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class SquareViewController: UIViewController {
    @IBOutlet weak var wheel: UIImageView!
    var link:CADisplayLink!
    var highlightedButton:UIButton!
    override func viewDidLoad() {
        // 转盘背景图片
        let imageView = UIImageView(image: UIImage(imageLiteral: "LuckyBackground"))
        imageView.frame = self.view.bounds
        self.view.insertSubview(imageView, atIndex: 0)
        // 获得屏幕scale,之后截取图片的时候会用到，不然图片截取之后是不规则的
        let scale = UIScreen.mainScreen().scale
        // 获得选项按钮背景图片
        let strology = UIImage(imageLiteral: "LuckyAstrology")
        let strologyPressed = UIImage(imageLiteral: "LuckyAstrologyPressed")
        // 获得截取图片的宽度
        let buttonW = strology.size.width / 12
        // 获得选项按钮的宽度
        let buttonFrame = CGRectMake(0, 0, buttonW, wheel.bounds.size.width * 0.5)
        // 设置图层的anchorPoint的值，旋转是围绕这个点旋转的
        let buttonLayerAnchorPoint = CGPointMake(0.5, 1)
        // 选项按钮放倒转盘中
        for var i = 0;i < 12;i++
        {
            let button = JinButton(type: UIButtonType.Custom)
            button.tag = i + 1
            button.frame = buttonFrame
            button.layer.anchorPoint = buttonLayerAnchorPoint
            button.center = CGPointMake(self.wheel.bounds.size.width * 0.5, self.wheel.bounds.size.width * 0.5)
            // 从大图片中截取一部分作为当前按钮的背景图片
            var buttonImage = CGImageCreateWithImageInRect(strology.CGImage, CGRectMake(buttonW * CGFloat(i) * scale, 0, buttonW * scale, strology.size.height * scale))
            button.setImage(UIImage(CGImage: buttonImage!), forState: UIControlState.Normal)
            buttonImage = CGImageCreateWithImageInRect(strologyPressed.CGImage, CGRectMake(buttonW * CGFloat(i) * scale, 0, buttonW * scale, strology.size.height * scale))
            
            // 设置选中状态下的图片
            button.setImage(UIImage(CGImage: buttonImage!), forState: UIControlState.Selected)
            button.setBackgroundImage(UIImage(imageLiteral: "LuckyRototeSelected"), forState: UIControlState.Selected)
            // 设置当前按钮的transform
            button.transform = CGAffineTransformMakeRotation(CGFloat(M_PI) / 6 * CGFloat(i))
            // 禁用高亮
            button.adjustsImageWhenHighlighted = false
            
            button.addTarget(self, action: "choiceNumber:", forControlEvents: UIControlEvents.TouchDown)
            self.wheel.addSubview(button)
        }
        // 添加开始选号按钮
        let choiceNumberButton = UIButton(type: UIButtonType.Custom)
        let choiceNumberButtonImage = UIImage(imageLiteral: "LuckyCenterButton")
        choiceNumberButton.bounds = CGRectMake(0, 0, choiceNumberButtonImage.size.width, choiceNumberButtonImage.size.height)
        choiceNumberButton.setBackgroundImage(choiceNumberButtonImage, forState: UIControlState.Normal)
        choiceNumberButton.setBackgroundImage(UIImage(imageLiteral: "LuckyCenterButtonPressed"), forState: UIControlState.Highlighted)
        choiceNumberButton.addTarget(self, action: "choiceNumberButtonClicked", forControlEvents: UIControlEvents.TouchDown)
        choiceNumberButton.center = self.wheel.center
        self.view.addSubview(choiceNumberButton)
        self.timer()
    }
    // 开始定时器
    func timer()
    {
        self.link = CADisplayLink(target: self, selector: "startRotation")
        self.link.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes)
    }
    // 旋转
    func startRotation()
    {
        self.wheel.transform = CGAffineTransformRotate(self.wheel.transform, CGFloat(M_PI) * 0.001)
    }
    // 选项按钮点击事件
    func choiceNumber(button:UIButton)
    {
        self.highlightedButton?.selected = false
        button.selected = true
        self.highlightedButton = button
    }
    func choiceNumberButtonClicked()
    {
        self.link?.invalidate()
        self.link = nil
        self.view.userInteractionEnabled = false
        UIView.transitionWithView(self.wheel, duration: 3, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
                [unowned self] in
                self.wheel.transform = CGAffineTransformRotate(self.wheel.transform, CGFloat(M_PI * 0.9))
            }, completion: {
                [unowned self] bool in
                let tag = Int(arc4random_uniform(12)) + 1
                let button:UIButton = self.wheel.viewWithTag(tag) as! UIButton
                self.choiceNumber(button)
                self.view.userInteractionEnabled = true
                //这里设置下延时执行，之前没用过的一种方式，这个参数有一些特别，而且没有提示。。。。记录下
                let minseconds = 3 * Double(NSEC_PER_SEC)
                let dtime = dispatch_time(DISPATCH_TIME_NOW, Int64(minseconds))
                if self.link == nil
                {
                    dispatch_after(dtime, dispatch_get_main_queue(), { [unowned self] () -> Void in
                        self.timer()
                    })
                }
                
        })
        
    }
}
